package com.zero.yygh.common.utils;

import org.apache.poi.ss.formula.functions.T;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * @author zero
 * @desc 随机验证码生成工具
 * @create 2021/4/2
 */
public class RandomUtil {
    private static final Random RANDOM = new Random();

    private static final DecimalFormat FOUR_DF = new DecimalFormat("0000");

    private static final DecimalFormat SIX_DF = new DecimalFormat("000000");

    /**
     * 获取四位随机验证码
     * @author zero
     * @date 2021/4/2 16:13
     * @return java.lang.String
     */
    public static String getFourBitRandom() {
        return FOUR_DF.format(RANDOM.nextInt(10000));
    }

    /**
     * 获取六位长度的随机验证码
     * @author zero
     * @date 2021/4/2 16:14
     * @return java.lang.String
     */
    public static String getSixBitRandom() {
        return SIX_DF.format(RANDOM.nextInt(1000000));
    }

    /**
     * 给定数组，抽取n个数据
     * @author zero
     * @date 2021/4/2 16:14
     * @param list 给定数组
     * @param n 抽取个数
     * @return java.util.ArrayList
     */
    public static List<T> getRandom(List<T> list, int n) {

        Random random = new Random();
        HashMap<Object, Object> hashMap = new HashMap<>(list.size());
        // 生成随机数字并存入HashMap
        for (int i = 0, len = list.size(); i <len; i++) {
            int number = random.nextInt(100) + 1;
            hashMap.put(number, i);
        }
        // 从HashMap导入数组
        Object[] robs = hashMap.values().toArray();
        List<T> r = new ArrayList<>();
        // 遍历数组并打印数据
        for (int i = 0; i < n; i++) {
            r.add(list.get((int) robs[i]));
        }
        return r;
    }

}
